<?php

namespace app\admin\model\kuerp;

use app\admin\model\Admin;
use addons\kuerp\model\Message;
use think\Model;
use traits\model\SoftDelete;
use Exception;

class Record extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'kuerp_record';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    const   CUSTOMER_TYPE = 1;//客户
	const   CONTACTS_TYPE = 2;//联系人
	const   CONTRACT_TYPE = 3;//合同
	const   LEADS_TYPE    = 4;//线索
    const   BUSINESS_TYPE    = 5;//商机

    // 追加属性
    protected $append = [
        'status_text'
    ];
    

    
    public function getStatusList()
    {
        return ['1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    //获取跟进记录列表
    public static function getList($relation_type, $relation_id) {
        return self::where(['relation_type' => $relation_type, 'relation_id' => $relation_id])->with(['file', 'admin'])->order('id desc')->select();
    }

    //获取附件记录
	public function file() {
		return $this->hasMany(RecordFile::class, 'record_id', 'id')->with('file')->field('record_id,file_id');
	}

    	//创建跟进记录
	public static function createRecord($params) {
		if(isset($params['files'])){
			$files = $params['files'];
			unset($params['files']);
		}else{
			$files='';
		}
        $staff  = Admin::info();
        if ($params['relation_type'] == self::CUSTOMER_TYPE) {//客户
            $create_staff_id = Customers::where(['id' => $params['relation_id']])->value('staff_member_id');

        } elseif ($params['relation_type'] == self::CONTACTS_TYPE) {//联系人
            $create_staff_id = 0;//CustomersUser::where(['id' => $params['relation_id']])->value('owner_staff_id');

        } elseif ($params['relation_type'] == self::CONTRACT_TYPE) {//合同
            $create_staff_id = GoodsSales::where(['id' => $params['relation_id']])->value('sale_user');

        }
        // elseif ($params['relation_type'] == self::LEADS_TYPE) {//线索
        //     $create_staff_id = Leads::where(['id' => $params['relation_id']])->value('owner_staff_id');

        // }elseif ($params['relation_type'] == self::BUSINESS_TYPE) {//
        //     $create_staff_id = Business::where(['id' => $params['relation_id']])->value('owner_staff_id');
        // }
        if(empty($create_staff_id)){
            $create_staff_id = $staff->id;
        }
        if(isset($params['next_time'])){
            $params['next_time']=$params['next_time']?:NULL;
        }
		$params['create_staff_id'] = $create_staff_id;
        $params['admin_id'] = $staff->id;
		$params['follow_time']     = date('Y-m-d H:i:s');
		$model                     = new self;

        $result = $model->allowField(true)->save($params);
		$lastId=$model->getLastInsID();
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($model->getError());
		}
		if ($files) {
			RecordFile::addFiles($files, $lastId);
		}

		if ($params['relation_type'] == self::CUSTOMER_TYPE) {//客户
		    if(isset($params['follow'])){
                $resCus['follow_status'] = $params['follow'];
            }
		    if(isset($params['next_time'])){
                $resCus['next_follow_time'] = strtotime($params['next_time']);
            }
            $resCus['last_follow_time'] = time();
			//同步跟进状态
			Customers::where(['id' => $params['relation_id']])->update($resCus);
			// if ($files) {
			// 	CustomerFile::addFiles($files, $params['relation_id']);
			// }
		}
        // elseif ($params['relation_type'] == self::CONTACTS_TYPE && isset($params['next_time'])) {//联系人
		// 	Contacts::where(['id' => $params['relation_id']])->update(['next_time' => $params['next_time']]);
		// 	if ($files) {
		// 		ContactsFile::addFiles($files, $params['relation_id']);
		// 	}
		// } elseif ($params['relation_type'] == self::CONTRACT_TYPE && isset($params['next_time'])) {//
		// 	if ($files) {
		// 		ContractFile::addFiles($files, $params['relation_id']);
		// 	}
		// }elseif ($params['relation_type'] == self::LEADS_TYPE && isset($params['next_time'])) {//
        //     Leads::where(['id' => $params['relation_id']])->update(['next_time' => $params['next_time']]);
		// 	if ($files) {
		// 		LeadsFile::addFiles($files, $params['relation_id']);
		// 	}
		// }elseif ($params['relation_type'] == self::BUSINESS_TYPE && isset($params['next_time'])) {//
        //     Business::where(['id' => $params['relation_id']])->update(['next_time' => $params['next_time']]);
        // }

		//通知上级
		if($staff->parentids && !in_array(2,$staff->group_ids)) {
			foreach ($staff->parentids as $parent) {
				Message::addMessage(Message::RECORD_TYPE, $lastId, $parent, $staff->id);
			}
		}

		return true;
	}



    public function customers()
    {
        return $this->belongsTo('Customers', 'relation_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function staff()
    {
        return $this->hasOne('app\admin\model\Admin', 'id', 'admin_id')->field('id,nickname,avatar');
    }
}
